package com.simple.car.loader.server.tools;

import android.os.Environment;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class FileCopy {

    private static String root = String.format("%s/com.simple.car.loader.server/data", Environment.getExternalStorageDirectory().getAbsolutePath());

    private static final String TAG = FileCopy.class.getName();

    public static File copy(File source) {
        File dir = new File(root);
        if (!dir.isDirectory()) {
            dir.mkdirs();
        }
        if (!source.isFile()) {
            Log.e(TAG, String.format("copy: 找不到源文件：%s", source.getAbsolutePath()));
            return null;
        }
        File file = new File(dir, source.getName());
        try (
                BufferedInputStream bufferedInputStream = new BufferedInputStream(Files.newInputStream(source.toPath()));
                BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(Files.newOutputStream(file.toPath()))
        ) {
            byte [] data = new byte[8 * 1024];
            int index;
            while ((index = bufferedInputStream.read(data)) != -1){
                bufferedOutputStream.write(data, 0, index);
            }
        } catch (IOException e) {
            Log.e(TAG, e.getMessage(), e);
            file.delete();
            return null;
        }
        return file;
    }
}
